package com.cwt_taxi_xa.service;

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.protocol.DispatchCenterUsers;
import com.cwt_taxi_xa.protocol.Encoder;
import com.cwt_taxi_xa.protocol.NianBaoUtil;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.HttpUtils;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.StringParser;
import com.cwt_taxi_xa.util.Tools;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DvrService extends Service {

	private String TAG = "DvrService";

	public static boolean isconnect_tl = false;//通立dvr是否连接

	Socket socket;
	boolean reading = false;
	InputStream ist;
	OutputStream ost;
	int size;
	byte[] buffer = new byte[1024];

	Timer timer;

	long receiverTime = 0;

	private static DvrService instance;

	public static DvrService getInstance() {
		return instance;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}


	Socket socket_dd;
	boolean reading_dd = false;
	InputStream ist_dd;
	OutputStream ost_dd;
	int size_dd;
	byte[] buffer_dd = new byte[1024];

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance = this;

		connectDVR();
		startRead();
		startHeart();

//		AppLog.e("22222222222222222222222222222---0");
//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				try {
//					socket_dd = new Socket("211.162.125.93", 5703);
//					AppLog.e("22222222222222222222222222222---1");
//					ist_dd = socket_dd.getInputStream();
//					ost_dd = socket_dd.getOutputStream();
//					AppLog.e("22222222222222222222222222222---2");
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}).start();
//		startRead_dd();
//		AppLog.e("22222222222222222222222222222---3");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		reading = false;
		isconnect_tl = false;
		closeDVR();
	}

	boolean test = false;
	public static long signtime = 0;
	public void onClick(int key){
		if(System.currentTimeMillis()-signtime<1000*60*60){
			try {
				if(SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr)==2){
					//郑工DVR按键指令
					switch (key) {
						case 16:
							sendHttpkey(38);
							break;
						case 17:
							sendHttpkey(40);
							break;
						case 18:
							sendHttpkey(37);
							break;
						case 19:
							sendHttpkey(39);
							break;
						case 13:
							sendHttpkey(13);
							break;
						case 15:
							sendHttpkey(76);
							break;
						case 14:
							sendHttpkey(27);
							break;
					}
				}else{
					//通立DVR指令
					sendDataToDvr(getKeydata(1, key));
					sendDataToDvr(getKeydata(0, key));
				}


				AppLog.e(Integer.toHexString(key));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			AlertDialog.Builder customizeDialog = new AlertDialog.Builder(MainApplication.topActivity);
			final EditText dialogView = new EditText(MainApplication.topActivity);
			dialogView.setInputType(InputType.TYPE_CLASS_NUMBER);
			customizeDialog.setTitle("请输入密码");
			customizeDialog.setView(dialogView);
			customizeDialog.setPositiveButton("确定",new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// 获取EditView中的输入内容
					String mima = dialogView.getText().toString();
					String mm = new SimpleDateFormat("HHddMMyy").format(new Date());
					//if(mima!=null&&mima.equals(mm) ){
					if(mima!=null&&mima.equals(Constants.PASS_WORD)){
						signtime = System.currentTimeMillis();
						Toast.makeText(MainApplication.topActivity, "验证成功，一小时内有效", 1500).show();
					}else{
						Toast.makeText(MainApplication.topActivity, "验证失败", 1000).show();
					}
				}
			});
			customizeDialog.setNegativeButton("取消", null);
			customizeDialog.show();
		}
	}

	/**
	 * 郑工DVR按键指令
	 * @param key
	 */
	public void sendHttpkey(final int key){
		if(key==50||key==65) return;
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					String url = null;
					url = "http://"+SPConstants.SPV_dvrip_zg+":6681/input_remote_key?key="+key;
					HttpEntity httpEntity = HttpUtils.getEntity(url, null, HttpUtils.METHOD_GET);
					InputStream inputStream = HttpUtils.getStream(httpEntity);
					String json = StringParser.parse(inputStream);
					inputStream.close();
					if(json.contains("200")){
						AppLog.e("----------->"+json);
					}else{
						AppLog.e("400----------->"+json);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

	/**
	 * 郑工DVR指令
	 * @param key
	 */
	public void sendHttpGetSet(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					String url = null;
					/**
					 * centerPara.centerIpArray[0].host=120.24.89.199
					 centerPara.centerIpArray[0].port=9970
					 */
//					url = "http://192.168.0.75:6681/get_dvr_para?terminalPara.phoneNumber=&netdevWiredPara.netset.ipaddr=&netdevWiredPara.netset.gateway=";
					url = "http://"+SPConstants.SPV_dvrip_zg+":6681/set_dvr_para?terminalPara.phoneNumber="+DeviceBiz.getDeviceCode()
							+"&centerPara.centerIpArray[0].host=0"
							+"&terminalPara.vehicleNumber="+DeviceBiz.getCarNumberSingleLetter()
							+"&terminalPara.companyName="+ URLEncoder.encode(getCompanyname(),"GBK")
							+"&terminalPara.driverName="+ URLEncoder.encode(getDriverName(),"GBK");

					HttpEntity httpEntity = getEntity(url, null, HttpUtils.METHOD_GET);
					InputStream inputStream = HttpUtils.getStream(httpEntity);
					String json = StringParser.parse(inputStream);
					inputStream.close();
					if(json.contains("200")){
						AppLog.e("----------->"+json);
					}else{
						AppLog.e("400----------->"+json);
					}
				} catch (Exception e) {
//					e.printStackTrace();
				}

			}
		}).start();
	}

	public HttpEntity getEntity(String uri, List<NameValuePair> params,
									   int method) throws IOException {
		HttpEntity entity = null;
		// 创建客户端对象
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "GBK");
		// 创建请求对象
		HttpUriRequest request = null;
		switch (method) {
			case HttpUtils.METHOD_GET:
				StringBuilder sb = new StringBuilder(uri);
				if (params != null && !params.isEmpty()) {
					sb.append('?');
					for (NameValuePair pair : params) {
						sb.append(pair.getName()).append('=')
								.append(pair.getValue()).append('&');
					}
					sb.deleteCharAt(sb.length() - 1);
				}
				request = new HttpGet(sb.toString());
				Log.d(TAG,"HttpUtil.uri+++++++++++++++"+uri);
				break;
			case HttpUtils.METHOD_POST:
				if(params != null && params.size()!=0){
					Log.d(TAG,"HttpUtil.uri+++++++++++++++"+uri+"?"+params.toString());
				}
				request = new HttpPost(uri);
				if (params != null && !params.isEmpty()) {
					// 创建请求实体对象
					UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(
							params, HTTP.UTF_8);
					// 设置请求实体
					((HttpPost) request).setEntity(reqEntity);
				}
				break;
		}
		// 执行请求获取相应对象
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			entity = response.getEntity();
		}
		return entity;
	}

	private String getCompanyname(){
		String result = "";
		try {
			if(!TextUtils.isEmpty(Constants.sijiinfo.getCompanyname())){
				result = Constants.sijiinfo.getCompanyname();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private String getDriverName(){
		String result = "";
		try {
			if(!TextUtils.isEmpty(Constants.sijiinfo.getName())){
				result = Constants.sijiinfo.getName();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void onTouch(int x, int y){
		try {
			sendDataToDvr(getTouch(1, x, y));
			sendDataToDvr(getTouch(0, x, y));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void connectDVR() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					socket = new Socket("192.168.141.1", 8640);
					ist = socket.getInputStream();
					ost = socket.getOutputStream();
					AppLog.e("-------------------------1");
					ost.write(getSign());
					AppLog.e("-------------------------2");
				} catch (Exception e) {
//					e.printStackTrace();
				}
			}
		}).start();
	}

	void closeDVR() {
		try {
			if(ist!=null){
				ist.close();
				ist = null;
			}
			if(ost!=null){
				ost.close();
				ost = null;
			}
			if(socket!=null){
				socket.close();
				socket = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	void startRead(){
		reading = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (reading) {
					try {
						if(socket!=null&&ist!=null&&ist.available()>0){
							size = ist.read(buffer);
//							AppLog.e("-------------------------reading:" + size);
							if (size > 0) {
								isconnect_tl = true;
								receiverTime = System.currentTimeMillis();
//								AppLog.e(size + "------" + Tools.parseByte2HexStr2(Tools.byteTobyte(buffer, 0, size)));
								NianBaoUtil.nbtldvr(buffer, size);
							}
						}else{
							Thread.sleep(200);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
//	void startRead_dd(){
//		reading_dd = true;
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				while (reading_dd) {
//					try {
//						if(socket_dd!=null&&ist_dd!=null&&ist_dd.available()>0){
//							size_dd = ist_dd.read(buffer_dd);
//							AppLog.e("-------------------------reading_dd:" + size_dd);
//							if (size_dd > 0) {
//								AppLog.e(size_dd + "------" + Tools.parseByte2HexStr(Tools.byteTobyte(buffer_dd, 0, size_dd)));
//							}
//						}else{
//							Thread.sleep(200);
//						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			}
//		}).start();
//	}






	int fbcount = 0;
	byte[] pcbuffer = new byte[1024*100];
	int pcbindex = 0;

	byte[] data_order;
	public void onOrder( byte[] data){
		int size = data.length;

		if(fbcount>0){
			data_order = new byte[size];
			int index = 0;
			for (int i = 0; i < size; i++) {
				if(data[i]==0x7D){
					if(data[i+1]==1){
						data_order[index] = 0x7D;
					}else{
						data_order[index] = 0x7E;
					}
					i++;
				}else{
					data_order[index] = data[i];
				}
				index++;
			}

			fbcount--;
			try {
				System.arraycopy(data_order, 11, pcbuffer, pcbindex, index-13);
				AppLog.e("分包照片第二包长度："+(index-13));
				pcbindex+=index-13;
				AppLog.e("分包照片总长度："+pcbindex);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(fbcount==0){
				byte[] result = new byte[pcbindex];
				System.arraycopy(pcbuffer, 0, result, 0, pcbindex);
				FloatService.onTLPIC(result);
			}
			return;
		}


		if(size<2000||isTCdata(Tools.byteTobyte(data, 0, 3))){
			data_order = data;
			data_order = Tools.yxReversal(data_order);
			String data_str = Tools.parseByte2HexStr(data_order);
			AppLog.e("dvr传来信息："+data_order.length+"---"+Tools.parseByte2HexStr(data_order));

			int mid = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(data_order, 1, 2)), 16);
			int lsn = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(data_order, 5, 2)), 16);
			if(mid!=0x8001){
				sendYD(mid, lsn);
			}

			if(data_str.startsWith("7E8806")){
				//透传上平台
				int mid_905 = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(data_order, 7, 2)), 16);
				if(mid_905!=0x0200){//忽略dvr的位置汇报

//					if(data_order.length>1000){
//						byte[] updata = Tools.byteTobyte(data_order, 9, data_order.length-2-9);
//						int count = updata.length/1000;
//						if(updata.length%1000!=0) count++;
//
//						for (int j = 0; j < count; j++) {
//							int subsize = (j==count-1)?updata.length-(1000*(count-1)):1000;
//							AppLog.e("分包长度："+subsize);
//							data_order = Encoder.getQhProtocol808Subpackage(Tools.byteTobyte(updata, j*1000, subsize), mid_905, count, j+1);
//							DispatchCenterUsers.witeMsg(data_order);
//						}
//
//					}else{
					data_order = Encoder.getQhProtocol808(Tools.byteTobyte(data_order, 9, data_order.length-2-9), mid_905);
					DispatchCenterUsers.witeMsg(data_order);
//					}

				}
			}
		}else{
			AppLog.e("收到照片，长度："+size);
			data_order = new byte[size];
			int index = 0;
			for (int i = 0; i < size; i++) {
				if(data[i]==0x7D){
					if(data[i+1]==1){
						data_order[index] = 0x7D;
					}else{
						data_order[index] = 0x7E;
					}
					i++;
				}else{
					data_order[index] = data[i];
				}
				index++;
			}
			if(data_order[3]==-1){
				AppLog.e("分包照片");
				fbcount = data_order[8];
				fbcount--;
				try {
					System.arraycopy(data_order, 20, pcbuffer, 0, index-22);
					pcbindex = index-22;
					AppLog.e("分包照片第一包长度："+pcbindex);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				data_order = Tools.byteTobyte(data_order, 16, index-18);
				FloatService.onTLPIC(data_order);


//				File f;
//				FileOutputStream fos;
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//				try {
//					f = new File("/mnt/sdcard/APP-PIC_test.jpg");
//					if(f.exists()) f.delete();
//					fos = new FileOutputStream(f);
//					fos.write(data_order);
//					fos.flush();
//					fos.close();
//					AppLog.e("拍照结束");
//				} catch (Exception e) {
//					e.printStackTrace();
//				}


			}




		}
	}


	public boolean isTCdata(byte[] data){
		return Tools.parseByte2HexStr(data).equals("7E8806");
	}


	byte[] data_yd = new byte[5];
	public void sendYD(int mid, int lsn){
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(lsn, 2), 0, data_yd, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(mid, 2), 0, data_yd, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(0, 1), 0, data_yd, num, 1);
		sendDataToDvr(getIntactMsg(getHead(0x0001, data_yd.length), data_yd));
	}


	public String apn = "UNIM2M.NJM2MAPN";
	public String dvrip = "180.167.106.70";
	public int port37 = 10000;
	public int port38 = 11000;
	public void sendSet(String id, String carcode){


		byte[] data_set = new byte[carcode.getBytes().length+17+12+apn.getBytes().length+dvrip.getBytes().length+4];


		int num = 0;
		System.arraycopy(Tools.int2Bytes2(6, 1), 0, data_set, num, 1);
		num += 1;


		System.arraycopy(Tools.int2Bytes2(1, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(10, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(id.getBytes(), 0, data_set, num, 10);
		num += 10;


		System.arraycopy(Tools.int2Bytes2(2, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(carcode.getBytes().length, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(carcode.getBytes(), 0, data_set, num, carcode.getBytes().length);
		num += carcode.getBytes().length;

//		 0x0022:UNIM2M.NJM2MAPN
//		 0x0036:180.167.106.70
//		 0x0037:10000
//		 0x0038:11000
		System.arraycopy(Tools.int2Bytes2(0x22, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(apn.getBytes().length, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(apn.getBytes(), 0, data_set, num, apn.getBytes().length);
		num += apn.getBytes().length;

		System.arraycopy(Tools.int2Bytes2(0x36, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(dvrip.getBytes().length, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(dvrip.getBytes(), 0, data_set, num, dvrip.getBytes().length);
		num += dvrip.getBytes().length;

		System.arraycopy(Tools.int2Bytes2(0x37, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(2, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(Tools.int2Bytes2(port37, 2), 0, data_set, num, 2);
		num += 2;

		System.arraycopy(Tools.int2Bytes2(0x38, 2), 0, data_set, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(2, 1), 0, data_set, num, 1);
		num += 1;
		System.arraycopy(Tools.int2Bytes2(port38, 2), 0, data_set, num, 2);
		num += 2;

		sendDataToDvr(getIntactMsg(getHead(0x0401, data_set.length), data_set));
	}

	public void sendDataToDvr(byte[] data){
		if(socket!=null&&ost!=null){
			try {
				ost.write(data);
				AppLog.e("向dvr写出数据："+Tools.parseByte2HexStr(data));
			} catch (Exception e) {
//				e.printStackTrace();
			}
		}

		if(System.currentTimeMillis()-receiverTime>30000){
			AppLog.e("dvr网络断开重连");
			isconnect_tl = false;
			closeDVR();
			connectDVR();
			AppLog.saveTxt2("socket断开重连");
		}
	}

	//临时测试用。。。
	public void chonglianceshi(){
		isconnect_tl = false;
		closeDVR();
		connectDVR();
	}



	void startHeart(){
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				sendDataToDvr(getHeartBeat());
			}
		};
		timer = new Timer();
		timer.schedule(task, 1000, 20000);
	}

	public void sendFaceView(int i){

		if(SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr)==2){
			//郑工DVR按键指令
			if(i==0){
				sendHttpkey(50);
			}else{
				sendHttpkey(65);
			}
		}else{
			sendDataToDvr(getFaceView(i));
		}

	}

	/**
	 * 鉴权
	 *
	 * @return
	 */
	byte[] getSign() {
		byte[] body = new byte[8];
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(0, 2), 0, body, num, 2);// 0-通立标准功能
		num += 2;
		System.arraycopy(Tools.int2Bytes2(20, 2), 0, body, num, 2);// 5秒向dvr发一次心跳
		num += 2;
		System.arraycopy(Tools.int2Bytes2(0, 2), 0, body, num, 2);// dvr每1秒向安卓屏发一次gps
		num += 2;
		System.arraycopy(Tools.int2Bytes2(25, 2), 0, body, num, 2);// 安卓发送心跳不超过10秒
		num += 2;
		return getIntactMsg(getHead(0x0003, body.length), body);
	}

	/**
	 * 抓拍
	 * 通道--1、2、3、4
	 * @return
	 */
	public static int nowpicindex;
	public void sendPICOrder(int chn) {
		nowpicindex = chn;
		byte[] body = new byte[11];
		body[0] = (byte) chn;
		body[1] = 1;
		body[2] = 1;
		body[3] = 1;
		body[4] = 0;
		body[5] = (byte) 0xff;
		body[6] = 5;//质量0-5，越小质量越好
		body[7] = 50;//亮度0-100
		body[8] = 50;//对比度0-100
		body[9] = 50;//饱和度0-100
		body[10] = 50;//色度0-100
		try {
			sendDataToDvr(getIntactMsg(getHead(0x0703, body.length), body));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void send95Order(byte[] body){
		try {
			body = getIntactMsg(getHead(0x0806, body.length), body);

			sendDataToDvr(body);

//			AppLog.e("透传数据到dvr："+Tools.parseByte2HexStr(body));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 心跳
	 *
	 * @return
	 */
	byte[] getHeartBeat() {
		return getIntactMsg(getHead(0x0002, 0), null);
	}

	/**
	 * 按键
	 *
	 * @param type
	 * @param key
	 * @return
	 */
	byte[] getKeydata(int type, int key) {
		byte[] keydata = new byte[3];
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(type, 1), 0, keydata, num, 1);
		num += 1;
		System.arraycopy(Tools.int2Bytes2(key, 2), 0, keydata, num, 2);
		return getIntactMsg(getHead(0x0302, keydata.length), keydata);
	}

	/**
	 * 切换通道一主画面
	 *
	 */
	byte[] getFaceView(int i) {
		byte[] keydata = new byte[2];
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(i, 1), 0, keydata, num, 1);
		num += 1;
		System.arraycopy(Tools.int2Bytes2(i==0?2:1, 1), 0, keydata, num, 1);
		return getIntactMsg(getHead(0x0300, keydata.length), keydata);
	}

	/**
	 * 模拟触控
	 *
	 * @param type
	 *            1-左键按下； 0-左键放开； 3-右键按下； 2-右键放开
	 * @param x
	 *            0-4095
	 * @param y
	 *            0-4095
	 * @return
	 */
	byte[] getTouch(int type, int x, int y) {
		byte[] touch = new byte[5];
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(type, 1), 0, touch, num, 1);
		num += 1;
		System.arraycopy(Tools.int2Bytes2(x, 2), 0, touch, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(y, 2), 0, touch, num, 2);
		num += 2;
		return getIntactMsg(getHead(0x0301, touch.length), touch);
	}

	/**
	 * 获取消息头（不分包类型）
	 *
	 * @param id
	 *            消息id
	 * @param length
	 *            消息体长度
	 * @return
	 */
	int count = 0;
	byte[] getHead(int id, int length) {
		byte[] head = new byte[6];
		int num = 0;
		System.arraycopy(Tools.int2Bytes2(id, 2), 0, head, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(length, 2), 0, head, num, 2);
		num += 2;
		System.arraycopy(Tools.int2Bytes2(count, 2), 0, head, num, 2);
		num += 2;

		count++;
		if(count>=0xffff) count = 0;

		return head;
	}

	/**
	 * 获取完整消息包
	 *
	 * @param head
	 * @param body
	 * @return
	 */
	byte[] getIntactMsg(byte[] head, byte[] body) {
		if (body == null) {
			body = new byte[0];
		}
		byte[] data = new byte[head.length + body.length + 3];
		data[0] = 0x00;
		data[data.length - 1] = 0x00;
		data[data.length - 2] = 0;
		System.arraycopy(head, 0, data, 1, head.length);
		System.arraycopy(body, 0, data, 1 + head.length, body.length);
		for (int i = 1; i < data.length - 2; i++) {
			data[data.length - 2] = (byte) (data[data.length - 2] ^ data[i]);
		}
		String data_str = Tools.parseByte2HexStr2(data);
		data_str = data_str.replaceAll(" 7D ", " 7D 01 ");
		data_str = data_str.replaceAll(" 7E ", " 7D 02 ");
		data = Tools.parseHexStr2Byte(data_str);
		data[0] = 0x7E;
		data[data.length - 1] = 0x7E;

		return data;
	}

	public void reStartTLDVR() {
		// TODO Auto-generated method stub
		sendDataToDvr(getIntactMsg(getHead(0x0207, 1), new byte[]{0x00}));
	}





	/**
	 * 通过ping判断网络是否连接
	 * @return
	 */
//	public boolean Ping(String ip){
//		AppLog.e("Ping:"+ip);
//		boolean connect = false;
//		Runtime runtime = Runtime.getRuntime();
//		Process process;
//		AppLog.e("Ping-----1");
//		try {
//			process = runtime.exec("ping -c 2 -w 3000" + ip);
//			AppLog.e("Ping-----2");
//			InputStream is = process.getInputStream();
//			InputStreamReader isr = new InputStreamReader(is);
//			AppLog.e("Ping-----3");
//			BufferedReader br = new BufferedReader(isr);
//			String line = null;
//			StringBuffer sb = new StringBuffer();
//			AppLog.e("Ping-----4");
//			while ((line = br.readLine()) != null) {
//				sb.append(line);
//				AppLog.e("Ping-----5");
//			}
//			System.out.println("返回值为:"+sb);
//			AppLog.e("Ping-----6");
//			is.close();
//			isr.close();
//			br.close();
//			AppLog.e("Ping-----7");
//
//			if (null != sb && !sb.toString().equals("")) {
//				if (sb.indexOf("TTL") > 0
//						||sb.indexOf("ttl") > 0
//						) {
//					// 网络畅通
//					connect = true;
//				} else {
//					// 网络不畅通
//					connect = false;    
//				}     
//			}     
//			AppLog.e("Ping-----8");
//		} catch (IOException e) {    
//			e.printStackTrace();    
//			AppLog.e("Ping-----9");
//		}     
//		return connect;    
//	} 







}
